package com.example.demo3.interceptor;


import com.alibaba.fastjson2.JSONObject;
import com.example.demo3.data.MessageKey;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * 实现握手拦截器
 *
 * 要点解析：
 *
 * HandshakeInterceptor用来拦截客户端第一次连接服务端时的请求，即客户端连接/webSocket/{INFO}时，我们可以获取到对应INFO的信息。
 * 实现beforeHandshake方法，进行用户信息保存，这里我们将用户名和房间号保存到Session上。
 *
 */
public class WebSocketInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        if (serverHttpRequest instanceof ServletServerHttpRequest) {
            System.out.println("进来webSocket的地址：" + serverHttpRequest.getURI().getPath());
            String INFO = serverHttpRequest.getURI().getPath().split("INFO=")[1];
            if (INFO != null && INFO.length() > 0) {
                JSONObject jsonObject = JSONObject.parseObject(INFO);
                String command = jsonObject.getString("command");
                if (MessageKey.ENTER_COMMAND.equals(command)) {
                    System.out.println("当前session的ID=" + jsonObject.getString("name"));
                    map.put(MessageKey.KEY_WEBSOCKET_USERNAME, jsonObject.getString("name"));
                    map.put(MessageKey.KEY_ROOM_ID, jsonObject.getString("roomId"));
                }
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        System.out.println("进来webSocket的afterHandshake拦截器！");
    }
}
